import prompt from '@ohos.promptAction';
import { Log } from '../../common/utils/log';
import { RuleFactory } from './rule/RuleFactory'

//表单验证
export async function validateForm(form, rules): Promise<boolean> {
  //未找到form则忽略
  if (!form) {
    return true;
  }
  let fields = Object.keys(form)
  for (let i = 0; i < fields.length; i++) {
    const name = fields[i]
    let rule = rules[name]
    Log.info('循环表单域', name, form[name])
    if (!rule || !(rule instanceof Array)) {
      //校验规则不合法则忽略
      continue;
    }
    for (let j = 0; j < rule.length; j++) {
      let item = rule[j]
      let tool = RuleFactory.getRule(item)
      if (tool) {
        if (!await tool.validate(form[name], item, form)) {
          return false;
        }
      } else {
        Log.error('不支持此类型校验规则忽略', item)
      }
    }
  }
  return true;
}

